package com.dlm.controller;

import com.dlm.config.CacheContext;
import com.dlm.dao.Item;
import com.dlm.dao.TItem;
import com.dlm.dao.Users;
import com.dlm.sdk.api.OpenIdApi;
import com.dlm.sdk.kit.SignatureCheckKit;
import com.dlm.service.IItemService;
import com.dlm.service.IUsersService;
import com.dlm.service.impl.ItemServiceImpl;
import com.dlm.service.impl.UsersServiceImpl;
import com.dlm.util.TypeUtil;
import com.google.common.base.Preconditions;
import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by chongsong on 15/2/1.
 * <mailto>chong.song@autonavi.com</mailto>
 */
public class ItemController extends BaseController{
    private Logger logger = Logger.getLogger(ItemController.class);
    private IItemService itemService = new ItemServiceImpl();
    private IUsersService usersService = new UsersServiceImpl();
    protected WxMpInMemoryConfigStorage wxMpConfigStorage;
    protected WxMpService wxMpService;

    public ItemController(){
        PropKit.use("config.properties", "UTF-8");
        wxMpConfigStorage = new WxMpInMemoryConfigStorage();
        wxMpConfigStorage.setAppId(PropKit.get("appId"));
        wxMpConfigStorage.setSecret(PropKit.get("appSecret"));
        wxMpConfigStorage.setToken(PropKit.get("token"));
        wxMpConfigStorage.setAesKey(PropKit.get("encodingAesKey"));
        wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxMpConfigStorage);
    }

    public void index () {
        String code = getPara("code");
        System.out.println("******* code:" + code);
        if(StringUtils.isNotBlank(code)){
            String openId = OpenIdApi.getOpenIdByCode(code);
            Users users = usersService.findUserByOpenid(openId);
            if(users != null){
                getSession().setAttribute("phone", users.getLong(Users.tel));
                getSession().setAttribute("name", users.getStr(Users.nickname));
            }
            getSession().setAttribute("openid",openId);
            System.out.println("openid:" + getSession().getAttribute("openid"));
        }else{
            System.out.println("请使用微信登陆!");
        }
        //TODO 测试
//        getSession().setAttribute("openid","1");
//        getSession().setAttribute("phone", "18618127709");
//        getSession().setAttribute("name", "宋冲");
        render("index.html");
    }

    public void sign() {
        HttpServletRequest request = getRequest();
        StringBuffer url =  request.getRequestURL();
        if(request.getQueryString() != null){
            url.append("?"+request.getQueryString());
        }
        WxJsapiSignature signature = CacheContext.getInstance().getSign(wxMpService,url.toString());
        if(signature != null) {
            request.setAttribute("ticket", signature.getJsapiTicket());
            request.setAttribute("nonceStr", signature.getNoncestr());
            request.setAttribute("signature", signature.getSignature());
            request.setAttribute("timestamp", signature.getTimestamp());
            request.setAttribute("url", signature.getUrl());
            request.setAttribute("appId", wxMpConfigStorage.getAppId());
        }
        renderJsp("/views/wxTest.jsp");
    }

    @Before(POST.class)
    public void add() {
        UploadFile uploadFile = getFile();
//        String mainImg = getPara("mainImg");
        String name = getPara("name");
        int type = getParaToInt("type", 0);
        String desc = getPara("desc");
        String spendTime = getPara("spendTime");
        String takeTime = getPara("takeTime");
        String price = getPara("price");
        String oldPrice = getPara("oldPrice");
        String flow = getPara("flow");
        String function = getPara("function");
        String tips = getPara("tips");
        try {
            Preconditions.checkArgument(StringUtils.isNotBlank(name), "name不能为空!");
//            Preconditions.checkArgument(StringUtils.isNotBlank(mainImg), "mainImg不能为空!");
//            Preconditions.checkArgument(StringUtils.isNotBlank(desc), "desc不能为空!");
//            Preconditions.checkArgument(StringUtils.isNotBlank(spendTime), "spendTime不能为空!");
//            Preconditions.checkArgument(StringUtils.isNotBlank(takeTime), "takeTime不能为空!");
            Preconditions.checkArgument(StringUtils.isNotBlank(flow), "flow不能为空!");
            Preconditions.checkArgument(StringUtils.isNotBlank(function), "function不能为空!");
            Preconditions.checkArgument(StringUtils.isNotBlank(tips), "tips不能为空!");
//            Preconditions.checkArgument(TypeUtil.isDouble(price), "price不能为空,且必须为数字!");
        } catch (Exception e) {
            renderJson(makeDto(1,e.getMessage(),null));
            return;
        }
        Item item = new Item();
        item.set(Item.name, name);
        item.set(Item.type, type);
        item.set(Item.desc, desc);
        item.set(Item.spendTime, spendTime);
        item.set(Item.takeTime, takeTime);
        item.set(Item.price, price);
        item.set(Item.oldPrice, oldPrice);
        item.set(Item.flow, flow);
        item.set(Item.function, function);
        item.set(Item.tips, tips);
        boolean isSave = false;
        try {
            if(uploadFile != null){
                item.set(Item.mainImg, "/upload/" + uploadFile.getFileName());
            }
            isSave = itemService.add(item);
            if(isSave){
                renderJson(makeDto(0,"ok",null));
                return;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        renderJson(makeDto(1, "保存失败!", null));
    }

    public void del(){
        long id = getParaToLong("id", 0l);
        try {
            Preconditions.checkArgument(id > 0, "id不能为空且必须大于0!");
        } catch (Exception e) {
            renderJson(makeDto(1,e.getMessage(),null));
            return;
        }

        boolean isDel = false;
        try {
            isDel = itemService.delete(id);
            if(isDel){
                renderJson(makeDto(0,"ok",null));
                return;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        renderJson(makeDto(1,"删除失败",null));
    }

    public void find(){
        int pno = getParaToInt("pno", 1);
        if(pno <= 0){
            pno = 1;
        }
        int psize = getParaToInt("psize",100);
        String posX = getPara("posX");
        String posY = getPara("posY");
        int techId = getParaToInt("techId", -1);
        //TODO 设置city
        String city = getPara("city");
        //TODO 暂时写死到七宝.
        posX = "121.361238";
        posY = "31.159064";
        try {
            Preconditions.checkArgument(TypeUtil.isDouble(posX), "posX:经度不能为空,且必须为数字!");
            Preconditions.checkArgument(TypeUtil.isDouble(posY), "posY:维度不能为空,且必须为数字!");
        } catch (Exception e) {
            renderJson(makeDto(1,e.getMessage(),null));
            return;
        }
        try {
            Page<Item> page = itemService.findByPage(techId,pno, psize,TypeUtil.toDouble(posX), TypeUtil.toDouble(posY));
            renderJson(makeDtoPage(0,"ok",page));
            return;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        renderJson(makeDto(1,"查询失败",null));
    }

    public void findById(){
        long itemId = getParaToLong("id", 0L);
        try{
            Preconditions.checkArgument((itemId>0), "id必须为正整数!");
        }catch (Exception e){
            renderJson(makeDto(1,e.getMessage(),null));
            return;
        }
        try {
            Item item = itemService.findById(itemId);
            if(item != null){
                renderJson(makeDto(0,"ok",item));
            }
        } catch (Exception e) {
            renderJson(makeDto(1, e.getMessage(), null));
        }
    }

//////////////////////////////////店面自定义项目///////////////////////////
    public void addItem() {
        long techId = getParaToLong("techId",0L);
        long itemId = getParaToLong("itemId",0L);
        String name = getPara("name");
        String price = getPara("price");
        String oldPrice = getPara("oldPrice");
        String usePro = getPara("usePro");
        String spendTime = getPara("spendTime");
        try {
            Preconditions.checkArgument(StringUtils.isNotBlank(name), "name不能为空!");
            Preconditions.checkArgument(techId != 0L , "techId不能为空!");
            Preconditions.checkArgument(itemId != 0L , "itemId不能为空!");
            Preconditions.checkArgument(StringUtils.isNotBlank(usePro), "usePro不能为空!");
            Preconditions.checkArgument(StringUtils.isNotBlank(spendTime), "spendTime不能为空!");
            Preconditions.checkArgument(TypeUtil.isDouble(price), "price不能为空,且必须为数字!");
            Preconditions.checkArgument(TypeUtil.isDouble(oldPrice), "oldPrice不能为空,且必须为数字!");
        } catch (Exception e) {
            renderJson(makeDto(1,e.getMessage(),null));
            return;
        }
        TItem tItem = new TItem();
        tItem.set(TItem.name, name);
        tItem.set(TItem.price, TypeUtil.toDouble(price));
        tItem.set(TItem.oldPrice, TypeUtil.toDouble(oldPrice));
        tItem.set(TItem.spend_time, TypeUtil.toInt(spendTime));
        tItem.set(TItem.techId, techId);
        tItem.set(TItem.usePro, usePro);
        try {
            boolean save = tItem.save();
            if(save){
                Record record = new Record();
                record.set("item_id", itemId);
                record.set("ti_id",tItem.getLong("id"));
                Db.save("r_item", record);
                renderJson(makeDto(0, "ok", null));
                return;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        renderJson(makeDto(1, "保存失败!", null));
    }

    public void findItem() {
        try {
            String sql = "SELECT ti.id, ti.tech_id, t.`name` tech_name, ti.`name` tItem_name, ti.use_pro, ti.price, ti.old_price, ti.spend_time, i.`name` item_name FROM t_item ti LEFT JOIN r_item ri ON ti.id = ri.ti_id LEFT JOIN item i ON ri.item_id = i.id LEFT JOIN technician t ON t.id = ti.tech_id";
            List<Record> records = Db.find(sql);
            Page page = new Page(records, 1, 1000, 1, 100);
            renderJson(makeDtoPage(0, "ok", page));
            return;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        renderJson(makeDto(1, "保存失败!", null));
    }

    public void delItem() {
        try {
            long id = getParaToLong("id",0L);
            Preconditions.checkArgument(id != 0L, "id不能为空!");
            if(TItem.dao.deleteById(id)){
                Db.update("delete  from r_item where ti_id = " + id);
            }
            renderJson(makeDto(0, "ok", null));
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            renderJson(makeDto(1, e.getMessage(), null));
        }
    }

}
